package com.lantosec.hmrp.modules.uploads.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lantosec.hmrp.core.config.InitDataListener;
import com.lantosec.hmrp.core.util.DateUtils;
import com.lantosec.hmrp.modules.category.entity.AssetsImage;
import com.lantosec.hmrp.modules.category.service.IAssetsImageService;
import com.lantosec.hmrp.modules.uploads.entity.SysUploads;
import com.lantosec.hmrp.modules.uploads.mapper.SysUploadsMapper;
import com.lantosec.hmrp.modules.uploads.service.ISysUploadsService;
import lombok.extern.log4j.Log4j2;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;

/**
 * <p>
 * 系统上传数据 服务实现类
 * </p>
 *
 * @author AutoCode
 * @since 2020-02-19
 */
@Service
@Primary
@Log4j2
@SuppressWarnings("all")
public class SysUploadsServiceImpl extends ServiceImpl<SysUploadsMapper, SysUploads> implements ISysUploadsService {

    @Autowired
    private IAssetsImageService imageService;

    @Override
    public SysUploads saveUploads(MultipartFile file) {
        SysUploads sysUploads = new SysUploads();
        if (file.isEmpty()) {
            throw new NullPointerException("文件为空");
        }
        String yyyyMM = DateUtils.dateToStr(new Date(), "yyyyMM");

        // 获取文件名后缀名
        String suffix = file.getOriginalFilename();
        String prefix = suffix.substring(suffix.lastIndexOf(".") + 1);
        String filePath = null;
        String url = null;
        // 设置文件上传后的路径
        //判断后缀是否是图片类型，建立图片跟附件两个文件夹
        if (prefix.equals("jpg") || prefix.equals("gif") || prefix.equals("png") || prefix.equals("bmp")) {
            url = InitDataListener.imgPath  + yyyyMM + "/";
            filePath = InitDataListener.rootPath+ url;
            sysUploads.setMediaType(10);
        } else {
            url = InitDataListener.filePath+ yyyyMM + "/";
            filePath = InitDataListener.rootPath + url;
            sysUploads.setMediaType(20);
        }
        //附件名称由时间戳加随机数组成
        String fileName = new Date().getTime() + "." + prefix;
        //创建文件路径
        File _file = new File(filePath + fileName);
        // 检测是否存在目录
        if (!_file.getParentFile().exists()) {
            //假如文件不存在即重新创建新的文件已防止异常发生
            _file.getParentFile().mkdirs();
        }
        try {
            //transferTo（dest）方法将上传文件写到服务器上指定的文件
            file.transferTo(_file);
            //当图片大小大于1M,需要对图片进行压缩并保存
            if (prefix.equals("jpg") || prefix.equals("gif") || prefix.equals("png") || prefix.equals("bmp")) {
                if (file.getSize() > (1024 * 1024)) {
                    //创建文件夹存放压缩图片
                    String thumbnailPath = filePath + InitDataListener.thumbnailPath;
                    File thumbnailFile = new File(thumbnailPath + fileName);
                    if (!thumbnailFile.getParentFile().exists()) {
                        //假如文件不存在即重新创建新的文件已防止异常发生
                        thumbnailFile.getParentFile().mkdirs();
                    }
                    Thumbnails.of(_file).scale(0.25f).toFile(thumbnailFile);
                }
            }
            sysUploads.setSavePath(url);
            String thumbnailPath = null;
            if(file.getSize() > (1024 * 1024)){
                thumbnailPath = url + InitDataListener.thumbnailPath;
            }else{
                thumbnailPath = url;
            }
            sysUploads.setThumbnailPath(thumbnailPath);
            sysUploads.setUploadTime(new Date());   //上传时间
            sysUploads.setFileName(fileName);              //文件名
            sysUploads.setFileSize((file.getSize() / 1024));           //文件大小
            sysUploads.setFileSuffix(prefix);                  //文件后缀
            sysUploads.setUploadTitle(suffix);                 //文件标题
            baseMapper.insert(sysUploads);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sysUploads;
    }

    @Override
    public Boolean deleteFileById(String uploadId) {
        return baseMapper.deleteFileById(uploadId);
    }

    @Override
    public String thumbnailPath(String uploadId) {
        SysUploads sysUploads = baseMapper.selectOne(new QueryWrapper<SysUploads>()
                .eq("upload_id", uploadId));
        if(sysUploads != null){
            String thumbnailPath = sysUploads.getThumbnailPath() + sysUploads.getFileName();
            return InitDataListener.uploadsUrl + thumbnailPath;
        }else {
            return null;
        }
    }

    @Override
    public List pictureUrl(String uploadId) {
        List param = new ArrayList();
        if(StringUtils.isNotEmpty(uploadId)){
            List<String> s = Arrays.asList(uploadId.split(","));
            s.forEach(it->{
                Map map = new HashMap<>();
                String url = queryPictureUrlById(it);         //原图片路径
                String thumbnailPath = thumbnailPath(it);    //压缩图路径
                map.put("uploadId",it);
                map.put("url",url);
                map.put("thumbnailPath",thumbnailPath);
                param.add(map);
            });
        }
        return param;
    }

    @Override
    public String queryPictureUrlById(String uploadId) {
        String url = baseMapper.queryPictureUrlById(uploadId);
        if(url == null){
            return null;
        }
        return InitDataListener.uploadsUrl + url;
    }

    @Override
    public List<AssetsImage> assetsPictureUrl(String assetsId) {
        List param = new ArrayList();
        List<AssetsImage> list = imageService.list(new QueryWrapper<AssetsImage>()
                .eq(String.valueOf(AssetsImage.ColName.assets_id), assetsId));
        if(list.size() > 0){
            list.forEach(it->{
                String uploadId = it.getUploadId();
                Map map = new HashMap<>();
                String url = queryPictureUrlById(uploadId);         //原图片路径
                String thumbnailPath = thumbnailPath(uploadId);    //压缩图路径
                map.put("uploadId",uploadId);
                map.put("url",url);
                map.put("thumbnailPath",thumbnailPath);
                map.put("submitUser",it.getSubmitUser());
                map.put("submitTime",it.getSubmitTime());
                param.add(map);
            });
        }
        return param;
    }
}

